package v1

import (
	"blockchain_data/api/v1/request"
	"blockchain_data/handler"
	"blockchain_data/utils"
	"blockchain_data/utils/errmsg"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
)

//查询已连接的ws服务
func GetServer(c *gin.Context)  {
	bourse := c.Param("bourse")
	goods := c.Param("goods")
	server := c.Param("server")
	data,code := handler.FindSub(bourse,goods,server)
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"data":data,
		"message":errmsg.GetErrMsg(code),
	})
}

//打开ws服务
func OpenWs(c *gin.Context)  {
	var data request.AddSub
	c.ShouldBindJSON(&data)
	code := handler.AddSub(data.Bourse,data.Goods,data.Server,data.ContractCode)
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrMsg(code),
	})
}

//关闭ws服务
func CloseWs(c *gin.Context)  {
	var data request.CloseSub
	c.ShouldBindJSON(&data)
	code := handler.DelSub(data.Bourse,data.Goods,data.Server,data.ContractCode)
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrMsg(code),
	})
}

//获取数据
func GetData(c *gin.Context)  {
	var data request.GetData
	c.ShouldBindJSON(&data)
	bourse := c.Query("bourse")
	goods := c.Query("goods")
	server := c.Query("server")
	contract_code := c.Query("contract_code")
	time := c.Query("time")


	if time == ""{
		time = "fundingrate"
	}
	var filename = fmt.Sprintf("%s/data/%s/%s/%s/%s/%s.csv",utils.GetCurrentPath(),bourse,goods,server,contract_code,time)

	fmt.Println(filename)
	//打开文件
	fileTmp, errByOpenFile := os.Open(filename)
	defer fileTmp.Close()

	if os.IsExist(errByOpenFile) || errByOpenFile != nil {
		code := errmsg.ERROR_NOT_FILE
		c.JSON(http.StatusOK,gin.H{
			"status":code,
			"message":errmsg.GetErrMsg(code),
		})
		return
	}

	//返回文件流
	c.File(filename)

}